package net.daum.webtoon.android;

import net.daum.webtoon.android.session.SessionManager;
import net.daum.webtoon.android.util.Logger;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.webkit.CookieManager;
import android.webkit.HttpAuthHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class LoginActivity extends Activity {

	private static final String TAG = LoginActivity.class.getSimpleName();
	private WebView webView;
	private String url = "http://m.daum.net";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		webView = new WebView(LoginActivity.this);
		webView.setWebChromeClient(new CustomWebChromeClient());
		webView.setWebViewClient(new CustomWebViewClient(LoginActivity.this));
		initWebview(webView);
		webView.loadUrl(url);
		setContentView(webView);
	}

	private void initWebview(WebView webView) {
		webView.setVerticalScrollbarOverlay(true);
		WebSettings settings = webView.getSettings();
		settings.setJavaScriptEnabled(true);
		settings.setBuiltInZoomControls(true);
	}

	private class CustomWebViewClient extends WebViewClient {

		private final String TAG = CustomWebViewClient.class.getSimpleName();
		private ProgressDialog progressDialog;
		private Context context;

		public CustomWebViewClient(Context context) {
			this.context = context;
			progressDialog = new ProgressDialog(context);
			progressDialog.setMessage(getString(R.string.loading));
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
			progressDialog.show();
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			try {
				progressDialog.dismiss();
			} catch (Exception e) {
			}
			CookieManager cookieManager = CookieManager.getInstance();
			final String cookie = cookieManager.getCookie(url);
			Logger.i(TAG, "url:" + url);
			Logger.i(TAG, "cookie:" + cookie);
			if (cookie.length() > 500) {
				SessionManager.getInstance(context).setSessionCookie(cookie);
				setResult(RESULT_OK);
				finish();
			}
		}

		@Override
		public void onReceivedHttpAuthRequest(WebView view,
				HttpAuthHandler handler, String host, String realm) {
			super.onReceivedHttpAuthRequest(view, handler, host, realm);
			Logger.i(TAG, "view:" + view);
			Logger.i(TAG, "handler:" + handler);
			Logger.i(TAG, "host:" + host);
			Logger.i(TAG, "realm:" + realm);
		}

	}

	private class CustomWebChromeClient extends WebChromeClient {

	}

}
